import requests,os,time
from bs4 import BeautifulSoup
import ui_weather
from PyQt5.QtGui import QPixmap,QPainter
from PyQt5.QtWidgets import QWidget,QMessageBox,QApplication
class Weather(ui_weather.Ui_Form,QWidget):
	def __init__(self):
		super(Weather,self).__init__()
		self.ui = ui_weather.Ui_Form()
		self.ui.setupUi(self)
		isGetWeather = self.getweatherInfo()

		if not isGetWeather:
			QMessageBox.warning(self,"警告","天气信息未成功获得",QMessageBox.Ok)
			return
		else:
			self.displayInformation()

	def getweatherInfo(self):
		try:
			url = "https://tianqi.moji.com/weather/china/shandong/qingdao"
			soup = BeautifulSoup(requests.get(url).text,'html.parser')
			address = soup.find_all('div','comm_box')
			self.province = address[0].ul.contents[5].a.string
			self.city = address[0].ul.contents[7].string
			air = soup.find_all('div','left')
			url_airQuality =air[0].img.get('src')
			self.airQuality = air[0].em.string

			weather = soup.find_all('div','wea_weather')
			#天气信息图标链接
			url_weatherInfo = weather[0].img.get('src')
			#温度
			self.temperature = weather[0].em.string
			#天气信息
			self.weatherInfo = weather[0].b.string
			#更新时间
			self.upDateTime = weather[0].strong.string

			wea_about = soup.find_all('div','wea_about')
			#湿度
			self.humidity = wea_about[0].span.string
			#风力等级
			self.WindGrade = wea_about[0].em.string

			wea_tip = soup.find_all('div','wea_tips')
			#天气提示
			self.weatherTip1 = wea_tip[0].span.string
			self.weatherTip2 = wea_tip[0].em.string
			self.currentPath = os.path.abspath('.')
			root = self.currentPath + "/weatherIcon/"

			if not os.path.exists(root):
				os.mkdir(root)

			path = root + "weatherInfo" + ".png"
			with open(path,'w+b') as img:
				img.write(requests.get(url_weatherInfo).content)
			path = root + "airQuality" + ".png"
			with open(path,'w+b') as img:
				img.write(requests.get(url_airQuality).content)

		except:
			return False
		else:
			return True

	def displayInformation(self):

		self.ui.airQualityImg.setPixmap(QPixmap(self.currentPath+"/weatherIcon/airQuality.png"))
		self.ui.weatherInfoImg.setPixmap(QPixmap(self.currentPath+"/weatherIcon/weatherInfo.png"))
		self.ui.city.setText("{} {}".format(self.province,self.city))

		self.ui.weatherInfo.setText("{} {}°C".format(self.weatherInfo,self.temperature))
		self.ui.airQuality.setText("{}".format(self.airQuality))
		self.ui.weatherTip.setText("{}  {}\n{}:\n{}\n{}".format(self.humidity,self.WindGrade
										,self.weatherTip1,self.weatherTip2,self.upDateTime))



if __name__ == '__main__':
	import sys
	app = QApplication(sys.argv)
	win = Weather()
	win.show()
	sys.exit(app.exec_())